package middleware

import (
	"github.com/gin-gonic/gin"
	"jgame-api/service"
	"net/http"
)

// AuthToken
// 解析 token 如果 token 不存在或无效则报错
func AuthToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")

		if token == "" {
			token = c.Request.Header.Get("Authorization")
		}

		if token == "" {
			token = c.Request.FormValue("token")
		}

		if token == "" {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		uid, err := service.CheckToken(token)

		if err != nil {
			c.AbortWithStatus(http.StatusUnauthorized)
		}

		c.Set("uid", uid)
	}
}

// AuthTokenWithoutAbort
// 解析 token 如果 token不存在或无效则不处理
func AuthTokenWithoutAbort() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")

		if token == "" {
			token = c.Request.FormValue("token")
		}
		if token == "" {
			return
		}
		uid, err := service.CheckToken(token)

		if err != nil {
			return
		}
		c.Set("uid", uid)
	}
}
